<template>
  <el-dialog
    :title="areaInfo.stoAreaName + ' - 设置分类'"
    :visible="visible"
    width="1200px"
    :close-on-click-modal="false"
    :append-to-body="true"
    @close="handleClose"
  >
    <div style="display: flex; align-items: center;">
      <el-tree
        ref="treeRef"
        :data="treeData"
        :props="defaultProps"
        value-key="id"
        style="width: 400px;"
        show-checkbox
        :default-expand-all="true"
        :highlight-current="true"
        node-key="stuClassId"
        draggable
        :checked-keys="checkedKeys"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ data.nccStuName ? `(${data.nccStuCode})` + data.nccStuName : data.stuClassName }}</span>
          </span>
        </template>
      </el-tree>
      <!-- 添加箭头按钮 -->
      <div style="margin: 0 10px; display: flex; flex-direction: column; justify-content: center; height: 100%;">
        <el-button
          type="primary"
          icon="el-icon-right"
          @click="handleTransfer"
          style="margin-bottom: 10px;"
        ></el-button>
      </div>

      <el-table :data="tableList" border height="605px">
        <el-table-column type="index" label="序号" align="center"></el-table-column>
        <el-table-column prop="stoName" label="仓库名称" align="center"></el-table-column>
        <el-table-column prop="stoAreaName" label="库区名称" align="center"></el-table-column>
        <el-table-column prop="stuClassName" label="类型" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div slot="footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleFormSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  findTreeSkuTypeData,
} from '@/api/basic/PersonnelInformation.js'
import {
  getAllAreaRules, // 获取列表
  addAreaRules, // 新增
} from "@/api/index/yxl";

export default {
  name: 'FormulationDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    areaInfo: {
      type: Object,
      default: () => ({}),
    }
  },
  data() {
    return {
      treeData: [],
      loading: false,
      total: 0,
      apiTableList: [], // 从API获取的原始数据
      userSelectedList: [], // 用户选择的数据
      checkedKeys: [],  // 保存当前选中的节点的ID
      defaultProps: {
        children: 'children',
        label: 'nccStuName',
        disabled: this.isNodeDisabled  // 添加禁用属性
      },
    };
  },
  computed: {
    // 合并API数据和用户选择的数据
    tableList() {
      return [...this.apiTableList, ...this.userSelectedList];
    }
  },
  created() {
    this.getNccMaterialList();
    if (this.areaInfo.stoAreaId) {
      this.getList(this.areaInfo.stoAreaId);
    }
  },
  methods: {
    // 判断节点是否禁用
    isNodeDisabled(data) {
      return data.enableState !== '2';  // 只有 enableState 为 '2' 时才可选
    },
    // 获取列表
    getList(data) {
      getAllAreaRules({stoAreaId: data}).then(response => {
        this.apiTableList = response.data;
        this.restoreCheckedState(); // 弹框打开时恢复选中状态
      });
    },
    // 提交表单
    handleFormSubmit() {
      const allData = [...this.apiTableList, ...this.userSelectedList];
      addAreaRules({
        stoAreaId: this.areaInfo.stoAreaId,
        codeList: allData.map(item => item.stuClassId || item.id)
      }).then(() => {
        this.$message.success('保存成功');
        this.handleClose();
      }).catch(error => {
        this.$message.error('保存失败: ' + (error.message || '未知错误'));
      });
    },
    isDisabled(data, node) {
      return data.children;
    },

    // 删除库区类型
    handleDelete(row) {
      const apiIndex = this.apiTableList.findIndex(item => (item.stuClassId || item.id) === (row.stuClassId || row.id));
      if (apiIndex !== -1) {
        this.apiTableList.splice(apiIndex, 1);
      }
      const userIndex = this.userSelectedList.findIndex(item => (item.stuClassId || item.id) === (row.stuClassId || row.id));
      if (userIndex !== -1) {
        this.userSelectedList.splice(userIndex, 1);
      }

      // 取消选中左侧对应节点
      const node = this.$refs.treeRef.getNode(row.stuClassId); // 使用 stuClassId 代替 id
      if (node) {
        this.$refs.treeRef.setChecked(node, false);
      }

      this.$message.success('删除成功');
    },
    // 获取树
    getNccMaterialList() {
      findTreeSkuTypeData().then(response => {
        this.treeData = response.data;
      });
    },
    handleTransfer() {
      const checkedNodes = this.$refs.treeRef.getCheckedNodes();
      const newSelections = checkedNodes.filter(node =>
        !this.apiTableList.some(item => (item.stuClassId || item.id) === (node.stuClassId || node.id)) &&
        !this.userSelectedList.some(item => (item.stuClassId || item.id) === (node.stuClassId || node.id)) &&
        !node.children
      );

      this.userSelectedList = [
        ...this.userSelectedList,
        ...newSelections.map(node => ({
          stoName: this.areaInfo.stoName,
          stoAreaName: this.areaInfo.stoAreaName,
          stuClassName: node.stuClassName,
          stuClassId: node.stuClassId || node.id,
          id: node.id,
        }))
      ];

      this.checkedKeys = this.$refs.treeRef.getCheckedKeys();
    },
    // 关闭对话框
    handleClose() {
      // 在关闭对话框时取消选中状态
      this.userSelectedList.forEach(item => {
        const node = this.$refs.treeRef.getNode(item.stuClassId); // 使用 stuClassId 来查找
        if (node) {
          this.$refs.treeRef.setChecked(node, false);
        }
      });

      // 清空用户选择的数据
      this.userSelectedList = [];

      // 关闭弹框
      this.$emit('update:visible', false);
    },

    // 恢复选中状态
    restoreCheckedState() {
      this.apiTableList.forEach(item => {
        const node = this.$refs.treeRef.getNode(item.stuClassId); // 使用 stuClassId 来查找节点
        if (node) {
          this.$refs.treeRef.setChecked(node, true); // 设置节点为选中状态
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.pagination {
  margin-top: 16px;
  text-align: right;
}

.el-tree {
  height: 615px;
  overflow-y: auto;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
